package com.example.fridaykt.service.impl

import com.example.fridaykt.model.*
import com.example.fridaykt.service.SysMenuService
import com.example.fridaykt.vo.Page
import org.babyfish.jimmer.sql.kt.KSqlClient
import org.babyfish.jimmer.sql.kt.ast.expression.eq
import org.babyfish.jimmer.sql.kt.fetcher.newFetcher
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 * @author 27371
 * @description 针对表【sys_menu(菜单权限表)】的数据库操作Service实现
 * @createDate 2022-05-09 17:21:37
 */
@Service
@Transactional
class SysMenuServiceImpl(
    private val sqlClient: KSqlClient,
) : SysMenuService {

    override fun listWithTree(): List<SysMenu> {
        val res = sqlClient.createQuery(SysMenu::class) {
            select(table.fetch(RECURSIVE_FETCHER))
        }.execute()
        return res
    }

    override fun listWithTreeWithRole(userId: Long): List<SysMenu> {
        val res = sqlClient.createQuery(SysMenu::class) {
            where(table.sysRoles { roleId eq userId })
            select(table.fetch(RECURSIVE_FETCHER))
        }.execute()
        return res
    }

    override fun getMenuList(cur: Int, ps: Int): Page<SysMenu> {
        val res = sqlClient.createQuery(SysMenu::class) {
            select(table)
        }.fetchPage(cur - 1, ps)
        return Page<SysMenu>().apply {
            current = cur
            pageSize = ps
            records = res.rows
            total = res.totalPageCount
        }
    }

    override fun getMenuIdListByUserIdWithRole(uId: Long): List<Long> {
        val res = sqlClient.createQuery(SysMenu::class) {
            where(table.sysRoles {
                sysUsers {
                    userId eq uId
                }
            })
            select(table.menuId)
        }.execute()
        return res
    }

    companion object {
        private val RECURSIVE_FETCHER = newFetcher(SysMenu::class).by {
            allScalarFields()
            `children*`()
        }
    }
}




